import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class PurchaseManageFrame extends JFrame {
    private JTable purchaseTable;
    private DefaultTableModel tableModel;

    public PurchaseManageFrame() {
        setTitle("采购管理");
        setSize(1000, 600);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("采购单号");
        tableModel.addColumn("采购日期");
        tableModel.addColumn("采购数量");
        tableModel.addColumn("采购价格");
        tableModel.addColumn("供应商编号");
        tableModel.addColumn("货物编号");
        tableModel.addColumn("采购员编号");

        purchaseTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(purchaseTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加采购");
        JButton deleteBtn = new JButton("删除采购");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        // 添加布局
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 加载数据
        loadPurchaseData();

        // 添加事件监听
        addBtn.addActionListener(e -> {
            new PurchaseEditDialog(null).setVisible(true);
            loadPurchaseData();
        });

        deleteBtn.addActionListener(e -> deletePurchase());
        refreshBtn.addActionListener(e -> loadPurchaseData());
    }

    private void loadPurchaseData() {
        tableModel.setRowCount(0); // 清空表格

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM purchase");

            while (rs.next()) {
                Object[] row = {
                        rs.getString("pno"),
                        rs.getDate("pdate"),
                        rs.getInt("pnum"),
                        rs.getBigDecimal("pprice"),
                        rs.getString("ono"),
                        rs.getString("dno"),
                        rs.getString("bno")
                };
                tableModel.addRow(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.close(conn, stmt, rs);
        }
    }

    private void deletePurchase() {
        int selectedRow = purchaseTable.getSelectedRow();
        if (selectedRow >= 0) {
            String pno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除采购单号为 " + pno + " 的记录吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                Connection conn = null;
                PreparedStatement pstmt = null;

                try {
                    conn = DBUtil.getConnection();
                    pstmt = conn.prepareStatement("DELETE FROM purchase WHERE pno = ?");
                    pstmt.setString(1, pno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadPurchaseData();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                } finally {
                    DBUtil.close(conn, pstmt, null);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class PurchaseEditDialog extends JDialog {
    private JTextField pnoField, pdateField, pnumField, ppriceField, onoField, dnoField, bnoField;
    private boolean isEditMode;

    public PurchaseEditDialog(String pno) {
        if (pno == null) {
            setTitle("添加采购记录");
            isEditMode = false;
        } else {
            setTitle("修改采购记录");
            isEditMode = true;
        }

        setSize(500, 400);
        setModal(true);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(7, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("采购单号:"));
        pnoField = new JTextField();
        if (isEditMode) pnoField.setEditable(false);
        panel.add(pnoField);

        panel.add(new JLabel("采购日期(yyyy-MM-dd):"));
        pdateField = new JTextField();
        panel.add(pdateField);

        panel.add(new JLabel("采购数量:"));
        pnumField = new JTextField();
        panel.add(pnumField);

        panel.add(new JLabel("采购价格:"));
        ppriceField = new JTextField();
        panel.add(ppriceField);

        panel.add(new JLabel("供应商编号:"));
        onoField = new JTextField();
        panel.add(onoField);

        panel.add(new JLabel("货物编号:"));
        dnoField = new JTextField();
        panel.add(dnoField);

        panel.add(new JLabel("采购员编号:"));
        bnoField = new JTextField();
        panel.add(bnoField);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> savePurchase());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadPurchaseData(pno);
        }
    }

    private void loadPurchaseData(String pno) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement("SELECT * FROM purchase WHERE pno = ?");
            pstmt.setString(1, pno);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                pnoField.setText(rs.getString("pno"));
                pdateField.setText(rs.getDate("pdate").toString());
                pnumField.setText(String.valueOf(rs.getInt("pnum")));
                ppriceField.setText(rs.getBigDecimal("pprice").toString());
                onoField.setText(rs.getString("ono"));
                dnoField.setText(rs.getString("dno"));
                bnoField.setText(rs.getString("bno"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
    }

    private void savePurchase() {
        String pno = pnoField.getText().trim();
        String pdateStr = pdateField.getText().trim();
        String pnumStr = pnumField.getText().trim();
        String ppriceStr = ppriceField.getText().trim();
        String ono = onoField.getText().trim();
        String dno = dnoField.getText().trim();
        String bno = bnoField.getText().trim();

        // 验证输入
        if (pno.isEmpty() || pdateStr.isEmpty() || pnumStr.isEmpty() ||
                ppriceStr.isEmpty() || ono.isEmpty() || dno.isEmpty() || bno.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int pnum;
        double pprice;
        Date pdate;

        try {
            pnum = Integer.parseInt(pnumStr);
            pprice = Double.parseDouble(ppriceStr);
            pdate = Date.valueOf(pdateStr);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "数量和价格必须为数字", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this, "日期格式应为yyyy-MM-dd", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE purchase SET pdate=?, pnum=?, pprice=?, ono=?, dno=?, bno=? WHERE pno=?");
                pstmt.setDate(1, pdate);
                pstmt.setInt(2, pnum);
                pstmt.setDouble(3, pprice);
                pstmt.setString(4, ono);
                pstmt.setString(5, dno);
                pstmt.setString(6, bno);
                pstmt.setString(7, pno);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO purchase (pno, pdate, pnum, pprice, ono, dno, bno) VALUES (?, ?, ?, ?, ?, ?, ?)");
                pstmt.setString(1, pno);
                pstmt.setDate(2, pdate);
                pstmt.setInt(3, pnum);
                pstmt.setDouble(4, pprice);
                pstmt.setString(5, ono);
                pstmt.setString(6, dno);
                pstmt.setString(7, bno);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
    }
}